package cn.z2huo.knowledge.jdk8.designpattern.proxy.dynamic.example;

import java.io.IOException;
import java.lang.reflect.*;

/**
 * <p>
 *
 * @author z2huo
 */
class MyServiceInvocationHandler implements InvocationHandler {

    private final MyService myService;

    public MyServiceInvocationHandler() {
        this.myService = new MyServiceImpl();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理对象：" + proxy.getClass().getName());
        System.out.println(method.getName() + " before");
        Object object = method.invoke(myService, args);
        System.out.println(method.getName() + " after");
        return object;
    }

    public static void main(String[] args) throws ClassNotFoundException, IOException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//        MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
//        MyService proxy = (MyService) Proxy.newProxyInstance(MyService.class.getClassLoader(),
//                new Class[]{MyService.class}, myInvocationHandler);

        Class<? > proxyClazz = Proxy.getProxyClass(MyService.class.getClassLoader(), MyService.class);
        Constructor<? > ctor = proxyClazz.getConstructor(InvocationHandler.class);
        InvocationHandler myInvocationHandler = new MyServiceInvocationHandler();
        MyService proxy = (MyService) ctor.newInstance(myInvocationHandler);

        proxy.request();
        System.out.println();
        proxy.response();

        System.out.println();
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(proxy);
        System.out.println(invocationHandler);
    }

    @Override
    public String toString() {
        return "this is a InvocationHandler";
    }
}